package com.wakala.employment.fragment.recruit;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.alibaba.android.vlayout.layout.StickyLayoutHelper;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.leaf.library.StatusBarUtil;
import com.lljjcoder.Interface.OnCityItemClickListener;
import com.lljjcoder.bean.CityBean;
import com.lljjcoder.bean.DistrictBean;
import com.lljjcoder.bean.ProvinceBean;
import com.lljjcoder.style.cityjd.JDCityConfig;
import com.lljjcoder.style.cityjd.JDCityPicker;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.BottomPopupView;
import com.stx.xmarqueeview.XMarqueeView;
import com.wakala.employment.R;
import com.wakala.employment.adapter.base.delegate.SimpleDelegateAdapter;
import com.wakala.employment.adapter.base.delegate.SingleDelegateAdapter;
import com.wakala.employment.adapter.jobCategory.JobCategoryTreeVo;
import com.wakala.employment.adapter.marquee.MarqueeViewAdapter;
import com.wakala.employment.core.BaseFragment;
import com.wakala.employment.core.constants.Constants;
import com.wakala.employment.core.http.subscriber.NoTipRequestSubscriber;
import com.wakala.employment.databinding.FragmentRecruitListBinding;
import com.wakala.employment.fragment.finder.JobCategoryFragment;
import com.wakala.employment.http.TestApi;
import com.wakala.employment.http.bean.CategoryMenuVo;
import com.wakala.employment.http.bean.FilterConditionVo;
import com.wakala.employment.http.bean.ResumeInfoPage;
import com.wakala.employment.http.bean.ResumeInfoSearchRequest;
import com.wakala.employment.http.bean.ResumeInfoVo;
import com.wakala.employment.utils.TokenUtils;
import com.wakala.employment.utils.Utils;
import com.xuexiang.xhttp2.XHttpProxy;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xpage.annotation.Page;
import com.xuexiang.xpage.enums.CoreAnim;
import com.xuexiang.xpage.utils.GsonUtils;
import com.xuexiang.xui.adapter.recyclerview.RecyclerViewHolder;
import com.xuexiang.xui.utils.CollectionUtils;
import com.xuexiang.xui.widget.actionbar.TitleBar;
import com.xuexiang.xui.widget.imageview.RadiusImageView;
import com.xuexiang.xui.widget.textview.supertextview.SuperButton;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.tip.ToastUtils;
import com.yechaoa.yutils.ToastUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import co.lujun.androidtagview.TagContainerLayout;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link RecruitListFragment#} factory method to
 * create an instance of this fragment.
 */
@Page(anim = CoreAnim.none)
public class RecruitListFragment extends BaseFragment<FragmentRecruitListBinding> implements View.OnClickListener {

    public static final String TAG = RecruitListFragment.class.getSimpleName();
    private CategoryMenuVo categoryMenuVo;
    private ResumeInfoSearchRequest resumeInfoSearchRequest = new ResumeInfoSearchRequest();
    private SimpleDelegateAdapter<ResumeInfoVo> mResumeInfoAdapter;

    private LinearLayout container;

    /**
     * 条件过滤 - 城市
     */
    private SuperButton ssBtnRegion;
    /**
     * 工种过滤
     */
    private SuperButton ssBtnWorkKind;
    boolean isInit = false;


    int currentPage = 1;
    int pageSize = 10;

    private ArrayList<String> tagLayoutTags = new ArrayList<>();

    private ArrayList<JobCategoryTreeVo> selectedJobList = new ArrayList<>();

    @NonNull
    @Override
    protected FragmentRecruitListBinding viewBindingInflate(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, boolean attachToRoot) {
        return FragmentRecruitListBinding.inflate(inflater, container, attachToRoot);
    }

    /**
     * @return 返回为 null意为不需要导航栏
     */
    @Override
    protected TitleBar initTitle() {
        requireActivity().getWindow().setStatusBarColor(getResources().getColor(R.color.xui_config_color_light));
        StatusBarUtil.setDarkMode(requireActivity());
        return null;
    }

    @Override
    protected void initArgs() {
        super.initArgs();
        //获取传递过来的参数
        if (getArguments() != null) {
            Object obj = getArguments().get("data");
            if (obj instanceof CategoryMenuVo) {
                categoryMenuVo = (CategoryMenuVo) obj;
            }
        }

    }


    @Override
    public void onFragmentResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == Constants.REQ_RESULT_110) {
            //工种分类选择返回数据
            tagLayoutTags = data.getStringArrayListExtra("tagLayoutTags");
            selectedJobList = data.getParcelableArrayListExtra("selectedJobList");
            String kindText = "";
            for (String tagText : tagLayoutTags) {
                kindText += tagText + "、";
            }
            kindText = StringUtils.cutString(kindText, 0, kindText.length() - 1);
            if (tagLayoutTags.size() > 1) {
                ssBtnWorkKind.setText(tagLayoutTags.get(0) + "-等" + tagLayoutTags.size() + "个工种");
            } else {
                ssBtnWorkKind.setText(kindText);
            }
            StringBuilder jobCategoryIds = new StringBuilder();
            for (JobCategoryTreeVo jobCategoryTreeVo : selectedJobList) {
                jobCategoryIds.append(jobCategoryTreeVo.getId()).append(",");
            }
            if (jobCategoryIds.length() > 0) {
                resumeInfoSearchRequest.setJobCategory(jobCategoryIds.toString());
                getResumeInfoList("fresh");
            }

        } else if (resultCode == Constants.REQ_RESULT_112) {
            Map<Integer, List<FilterConditionVo>> selectedResultMap = (Map<Integer, List<FilterConditionVo>>) data.getSerializableExtra("selectedResultMap");
            Log.i("", GsonUtils.toJson(selectedResultMap));
        }
    }


    @Override
    protected void initViews() {
        // 1.设置VirtualLayoutManager
        VirtualLayoutManager virtualLayoutManager = new VirtualLayoutManager(getContext());
        binding.recyclerView.setLayoutManager(virtualLayoutManager);

        // 2.设置RecycledViews复用池大小（可选）
        RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();
        viewPool.setMaxRecycledViews(0, 20);
        binding.recyclerView.setRecycledViewPool(viewPool);

        //----------1.微信加群提示banner---------------------------
        SingleDelegateAdapter bannerWeiXinAdapter = new SingleDelegateAdapter(R.layout.adapter_vlayou_banner_weixin_item) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                List<String> data = new ArrayList<>();
                data.add("免费加入本地招人找活群");
                data.add("附件找人找活信息推送");
                data.add("优质创业项目推荐");
                data.add("超多赚钱机会分享");

                XMarqueeView xMarqueeView = (XMarqueeView) holder.findViewById(R.id.marquee);
                try {
                    xMarqueeView.setAdapter(new MarqueeViewAdapter(data, getContext()));
                } catch (Exception e) {
                    //catchsetAdapter重复设置adapter抛出异常的异常。
                    Log.w("", e.getMessage());
                }
                holder.click(R.id.rb_wei_chat, v -> {
                    ToastUtil.showToast("下滑关闭当前窗口");
                    new XPopup.Builder(getContext()).asCustom(new BottomPopupView(requireContext()) {
                        @Override
                        protected int getImplLayoutId() {
                            return R.layout.dialog_invite_view;
                        }

                        @Override
                        protected void onCreate() {
                            super.onCreate();

                        }
                    }).show();
                });
            }
        };

        //------2.简历条件筛选----------------------
        StickyLayoutHelper layoutHelper = new StickyLayoutHelper();
        //设置顶部固定
        layoutHelper.setStickyStart(true);
        // 设置偏移量(距离顶部或底部)
        //layoutHelper.setOffset(-50);
        // 宽与高的比例
        //layoutHelper.setAspectRatio(4);
        //设置背景色
        layoutHelper.setBgColor(getResources().getColor(R.color.black));
        //layoutHelper.setPadding(0, 16, 0, 0);
        layoutHelper.setMargin(0, 0, 0, 0);
        //layoutHelper.setZIndex(9999);
        //过滤简历
        SingleDelegateAdapter filterAdapter = new SingleDelegateAdapter(R.layout.adapter_vlayou_filter_recruit_item, layoutHelper) {
            @Override
            public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {
                //1.地区/城市
                ssBtnRegion = holder.findViewById(R.id.ssBtn_region);
                //2工种
                ssBtnWorkKind = holder.findViewById(R.id.ssBtn_work_kind);
                holder.click(R.id.ssBtn_region, v -> {
                    //地区
                    showCityPicker();
                });
                holder.click(R.id.ssBtn_work_kind, v -> {
                    //工种
                    //跳转到所有工种选择页面
                    //Intent intent = new Intent();
                    //intent.putExtra("type","RECRUIT");
                    // openPageForResult(JobCategoryFragment.class,101);
                    // openNewPage(JobCategoryFragment.class,"type","JOBFINDER");
                    openJobCategoryFragment();
                });
                //3.筛选
                holder.click(R.id.ssBtn_filter, v -> {
                    //筛选
                    //openPageForResult(ResumeFilterFragment.class,101);
                    //openNewPage(ResumeFilterFragment.class);
                    openNewPageForResult(ResumeFilterFragment.class.getSimpleName(), Constants.REQ_RESULT_112);
                });
                //4.数据初始化
                //--初始化简历过滤组件----
                if (null != categoryMenuVo) {
                    if (categoryMenuVo.getTarget() == 1) {
                        //工种
                        if (!categoryMenuVo.getJobCategoryNames().isEmpty()) {
                            if (categoryMenuVo.getJobCategoryNames().size() > 1) {
                                //binding.ssBtnWorkKinds.setText(categoryMenuVo.getJobCategoryNames().get(0)+"-等"+categoryMenuVo.getJobCategoryNames().size()+"个工种");
                            } else {
                                //binding.ssBtnWorkKinds.setText(categoryMenuVo.getJobCategoryNames().get(0));
                            }
                            //显示菜单名称
                            ssBtnWorkKind.setText(categoryMenuVo.getName());
                            //设置菜单配置的工种ID值，形式为：独立或逗号分隔的工种id 例如：工种id+“，”+工种id
                            resumeInfoSearchRequest.setJobCategory(categoryMenuVo.getUrl());
                           // getResumeInfoList("fresh");
                        }
                    } else if (categoryMenuVo.getTarget() == 2) {
                        //职位标签
                    } else if (categoryMenuVo.getTarget() == 3) {
                        //关键字 title关键字，关键字标签
                        binding.tvKeywords.setText(categoryMenuVo.getUrl());
                        resumeInfoSearchRequest.setKeywords(categoryMenuVo.getUrl());
                        //getResumeInfoList("fresh");
                    }
                }

                //-------------------------------------
            }
        };

        //---------------3.简历数据列表------------------------------
        LinearLayoutHelper linearLayoutHelper = new LinearLayoutHelper();
        mResumeInfoAdapter = new SimpleDelegateAdapter<ResumeInfoVo>(R.layout.adapter_recruit_card_view_list_item, linearLayoutHelper) {
            @Override
            protected void bindData(@NonNull RecyclerViewHolder holder, int position, ResumeInfoVo model) {
                if (model != null) {
                    //头型
                    RadiusImageView headImageView = holder.findViewById(R.id.iv_avatar);
                    if (Utils.isHttpAddress(TokenUtils.getmLoginUser().getAvatar())) {
                        // Uri uri = Uri.parse(user.getAvatar());
                        // binding.rivHeadPic.setImageURI(uri);
                        RequestOptions options = new RequestOptions()
                                .centerCrop()
                                .placeholder(R.color.color_f4)
                                .diskCacheStrategy(DiskCacheStrategy.ALL);
                        Glide.with(headImageView.getContext()).load(model.getAvatar())
                                .apply(options)
                                .into(headImageView);
                    }
                    //昵称
                    holder.text(R.id.tv_user_name, model.getNickname());
                    //性别
                    holder.text(R.id.tv_sex, model.getSexName());
                    //年龄
                    holder.text(R.id.tv_age, model.getAge() + "岁");
                    //民族
                    holder.text(R.id.tv_nation, model.getNation());
                    //工作年限
                    holder.text(R.id.tv_work_years, model.getWorkYearsName());
                    /**
                     * 职业偏好综合信息
                     */
                    holder.text(R.id.tv_title, model.getJobSummary());
                    //职业优势标签
                   /* FlowTagAdapter tagAdapter = new FlowTagAdapter(getContext());
                    FlowTagLayout flowTagLayout = holder.findViewById(R.id.flowlayout_tgs);
                    flowTagLayout.setAdapter(tagAdapter);
                    flowTagLayout.setTagCheckedMode(FlowTagLayout.FLOW_TAG_CHECKED_SINGLE);
                    tagAdapter.addTags(model.getJobTags());*/
                    TagContainerLayout mTagContainerLayout = (TagContainerLayout) holder.findViewById(R.id.flowlayout_tgs);
                    if (!CollectionUtils.isEmpty(model.getJobTags())) {
                        mTagContainerLayout.setTags(model.getJobTags());
                    }
                    //个人简介
                    holder.text(R.id.tv_summary, model.getIntroduce());


                    //holder.text(R.id.tv_tag, model.getTag());


                    //holder.text(R.id.tv_praise, model.getPraise() == 0 ? "点赞" : String.valueOf(model.getPraise()));
                    //holder.text(R.id.tv_comment, model.getComment() == 0 ? "评论" : String.valueOf(model.getComment()));
                    //holder.text(R.id.tv_read, "阅读量 " + model.getRead());
                    //holder.image(R.id.iv_image, model.getImageUrl());

                    //holder.click(R.id.card_view, v -> Utils.goWeb(getContext(), model.getDetailUrl()));
                    holder.click(R.id.card_view, view -> {
                        //跳转到工人详情
                        openNewPage(RecruitInfoFragment.class);
                    });
                }
            }
        };

        DelegateAdapter delegateAdapter = new DelegateAdapter(virtualLayoutManager);
        delegateAdapter.addAdapter(bannerWeiXinAdapter);
        delegateAdapter.addAdapter(filterAdapter);
        delegateAdapter.addAdapter(mResumeInfoAdapter);

        binding.recyclerView.setAdapter(delegateAdapter);
    }

    @Override
    protected void initListeners() {
        binding.ssBtnToBack.setOnClickListener(this);
        binding.ssBtnJobSearch.setOnClickListener(this);
        //下拉刷新
        binding.refreshLayout.setOnRefreshListener(refreshLayout -> {
            currentPage = 1;
            resumeInfoSearchRequest.setPage(1);
            getResumeInfoList("fresh");
        });
        //上拉加载
        binding.refreshLayout.setOnLoadMoreListener(refreshLayout -> {
            currentPage++;
            resumeInfoSearchRequest.setPage(currentPage);
            getResumeInfoList("more");
        });
        binding.refreshLayout.setDisableContentWhenRefresh(true);
        binding.refreshLayout.setDisableContentWhenLoading(true);
        binding.refreshLayout.autoRefresh();//第一次进入触发自动刷新，演示效果
    }

    /**
     * 需要在fragment每次切换都需要执行的方法，其他地方的方法因为viewpage框架缓存的原因只会执行一次。
     */
    @Override
    protected void startLazyData() {
        super.startLazyData();
        this.initTitle();
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if(id==R.id.ssBtn_toBack){
            popToBack();
        }else if(id==R.id.ssBtn_job_search){
            hideCurrentPageSoftInput();
            //搜索
            resumeInfoSearchRequest.setKeywords(binding.tvKeywords.getText().toString());
            getResumeInfoList("fresh");
        }
    }

    @SuppressLint("CheckResult")
    private void getResumeInfoList(String type) {
        if (StringUtils.isEmpty(type)) {
            ToastUtils.toast("刷新类型为空或不符合要求");
            return;
        }
         /*if(type.equals("fresh")){
            binding.refreshLayout.autoRefresh();
        }*/
        appLoadingDialog.show();
        resumeInfoSearchRequest.setLimit(pageSize);
        XHttpProxy.proxy(TestApi.IResumeService.class)
                .getResumeInfoList(resumeInfoSearchRequest)
                .subscribeWith(new NoTipRequestSubscriber<ResumeInfoPage>() {
                    @Override
                    protected void onSuccess(ResumeInfoPage commonPageApiResult) {
                        Log.i(TAG, "-------------招工信息列表------------------");
                        Log.i(TAG, GsonUtils.toJson(commonPageApiResult));

                        if (type.equals("fresh")) {
                            mResumeInfoAdapter.refresh(commonPageApiResult.getList());
                            binding.refreshLayout.finishRefresh();
                        } else if (type.equals("more")) {
                            if (commonPageApiResult.getList().isEmpty()) {
                                binding.refreshLayout.finishLoadMoreWithNoMoreData();
                                ToastUtils.toast("已更新到最新数据");
                            } else {
                                mResumeInfoAdapter.loadMore(commonPageApiResult.getList());
                                binding.refreshLayout.finishLoadMore();
                            }

                        }
                        mResumeInfoAdapter.notifyDataSetChanged();
                        appLoadingDialog.dismiss();
                        //ToastUtils.toast("已更新最新数据");
                        Log.i(TAG, "-------------招工信息列表------------------");
                    }

                    @Override
                    public void onError(ApiException e) {
                        super.onError(e);
                        binding.refreshLayout.finishRefresh();
                        ToastUtils.toast(e.getDisplayMessage());
                        appLoadingDialog.dismiss();
                        Log.i(TAG, "-------------招工信息列表-返回错误------------------");
                        Log.e(TAG, e.getMessage());
                    }

                });
    }

    /**
     * 显示省市区选择组件
     */
    private void showCityPicker() {
        //创建对象
        JDCityPicker cityPicker = new JDCityPicker();
        //初始化配置
        JDCityConfig jdCityConfig = new JDCityConfig.Builder().build();
        //设置显示的样式
        jdCityConfig.setShowType(JDCityConfig.ShowType.PRO_CITY);
        cityPicker.init(getContext());//初始化选择器
        cityPicker.setConfig(jdCityConfig);
        cityPicker.setOnCityItemClickListener(new OnCityItemClickListener() {
            @Override
            public void onSelected(ProvinceBean province,
                                   CityBean city, DistrictBean district) {//选中后的监听
                String cityName = city.getName();
                if (city.getName().equals("市辖区")) {
                    cityName = province.getName();
                }
                ssBtnRegion.setText(cityName);
                //更新求职意向 城市
                resumeInfoSearchRequest.setJobCityName(cityName);
                getResumeInfoList("fresh");
            }

            @Override
            public void onCancel() {
                //cancel监听
            }
        });
        //显示地区列表
        cityPicker.showCityPicker();
    }

    private void openJobCategoryFragment() {
        // openNewPage(JobCategoryFragment.class,"type","RECRUIT");
        Bundle bundle = new Bundle();
        bundle.putString("type", "RECRUIT");
        openNewPageForResult(JobCategoryFragment.class.getSimpleName(), bundle, Constants.REQ_RESULT_110);
        //openPageForResult(true, "ResumeFilterFragment", null, CoreAnim.slide, 102);
    }

}